package com.zl.task.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zl.task.dao.ServiceOrderMapper;
import com.zl.task.dao.ServiceProductMapper;
import com.zl.task.dto.ShopDTO;
import com.zl.task.pojo.ServiceEnterprised;
import com.zl.task.pojo.ServiceMechanism;
import com.zl.task.pojo.ServiceOrder;
import com.zl.task.pojo.ServiceProduct;
import com.zl.task.service.IServiceEnterprisedService;
import com.zl.task.service.IServiceMechanismService;
import com.zl.task.service.IServiceOrderService;
import com.zl.task.service.IServiceProductService;
import com.zl.task.util.OrderUtils;
import com.zl.task.vo.OrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import static com.zl.task.commom.ServiceCode.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yinlingeng
 * @since 2021-07-23
 */
@Service
public class ServiceOrderServiceImpl extends ServiceImpl<ServiceOrderMapper, ServiceOrder> implements IServiceOrderService {

    @Resource
    ServiceProductMapper productMapper;
    @Autowired
    private IServiceEnterprisedService enterprisedService;
    @Autowired
    private IServiceMechanismService mechanismService;
    @Autowired
    private IServiceProductService productService;

    /**
     * 订单展示
     * todo 订单状态orderStatus： 1.服务完成 2.正在服务 3.审核通过，等待服务 4.待审核 99.用户取消
     *
     * @return List<ServiceOrder>
     */
    @Override
    public List<OrderVo> listOrders(Integer orderStatus,String userType,Long userId) throws Exception {
        if (userType.equals(ENTERPRISE_TYPE)){
            if (orderStatus>0) {
                return listOrdersCommon( baseMapper.selectList(Wrappers.<ServiceOrder>lambdaQuery()
                        .eq(ServiceOrder::getOrderStatus,orderStatus)
                        .eq(ServiceOrder::getOrderEnterprised,userId)
                        .orderByDesc(ServiceOrder::getOrderTime)),userType,userId);
            }
            return listOrdersCommon(baseMapper.selectList(Wrappers.<ServiceOrder>lambdaQuery()
                    .orderByDesc(ServiceOrder::getOrderTime)
                    .eq(ServiceOrder::getOrderEnterprised,userId)),userType,userId);
        }else if (userType.equals(MECHANISM_TYPE)){
            if (orderStatus>0) {
                return listOrdersCommon(baseMapper.selectList(Wrappers.<ServiceOrder>lambdaQuery()
                        .eq(ServiceOrder::getOrderStatus,orderStatus)
                        .eq(ServiceOrder::getOrderMechanism,userId)
                        .orderByDesc(ServiceOrder::getOrderTime)),userType,userId);
            }
            return listOrdersCommon(baseMapper.selectList(Wrappers.<ServiceOrder>lambdaQuery()
                    .eq(ServiceOrder::getOrderMechanism,userId)
                    .orderByDesc(ServiceOrder::getOrderTime)),userType,userId);
        }
        throw new Exception("获取失败");
    }

    /**
     * 订单展示公共方法
     */
    public List<OrderVo>listOrdersCommon(List<ServiceOrder> serviceOrders,String userType,Long userId){
        ArrayList<OrderVo> orderVos = new ArrayList<>();
        List<ServiceProduct> serviceProducts = productService.listAllProduct();
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
        if (userType.equals(ENTERPRISE_TYPE)) {
            List<ServiceMechanism> serviceMechanisms = mechanismService.listMechanism();
            String enterpriseName = enterprisedService.getEnterprisedById(userId.toString()).getEnterpriseName();
            for (ServiceOrder serviceOrder : serviceOrders) {
                OrderVo orderVo = new OrderVo();
                orderVo.setOrderCode(serviceOrder.getOrderCode());
                orderVo.setOrderProduct(serviceProducts.stream().filter(serviceProduct -> serviceProduct.getProductId().toString().equals(serviceOrder.getOrderProduct())).findAny().orElse(null).getProductName());
                orderVo.setOrderMechanism(serviceMechanisms.stream().filter(serviceMechanism -> serviceMechanism.getMechanismId().toString().equals(serviceOrder.getOrderMechanism())).findAny().orElse(null).getMechanismName());
                orderVo.setOrderEnterprised(enterpriseName);
                orderVo.setOrderStatus(serviceOrder.getOrderStatus());
                String format = df.format(serviceOrder.getOrderTime().getTime());
                orderVo.setOrderTime(format);
                orderVo.setOrderRemarks(serviceOrder.getOrderRemarks());
                orderVo.setOrderCause(serviceOrder.getOrderCause());
                orderVos.add(orderVo);
            }

        }else if (userType.equals(MECHANISM_TYPE)){
            List<ServiceEnterprised> serviceEnterpriseds = enterprisedService.listEnterprised();
            String mechanismName = mechanismService.getMenchanismById(userId.toString()).getMechanismName();
            for (ServiceOrder serviceOrder : serviceOrders) {
                OrderVo orderVo = new OrderVo();
                orderVo.setOrderCode(serviceOrder.getOrderCode());
                orderVo.setOrderProduct(serviceProducts.stream().filter(serviceProduct -> serviceProduct.getProductId().toString().equals(serviceOrder.getOrderProduct())).findAny().orElse(null).getProductName());
                orderVo.setOrderMechanism(serviceEnterpriseds.stream().filter(serviceEnterprised -> serviceEnterprised.getEnterprisedId().toString().equals(serviceOrder.getOrderEnterprised())).findAny().orElse(null).getEnterpriseName());
                orderVo.setOrderEnterprised(mechanismName);
                orderVo.setOrderStatus(serviceOrder.getOrderStatus());
                String format = df.format(serviceOrder.getOrderTime().getTime());
                orderVo.setOrderTime(format);
                orderVo.setOrderRemarks(serviceOrder.getOrderRemarks());
                orderVo.setOrderCause(serviceOrder.getOrderCause());
                orderVos.add(orderVo);
            }
        }
        return orderVos;
    }

    /**
     * 订单进度更新（修改）
     * 机构用户
     * 用户订单进程不得降近
     * @return Boolean
     */
    @Override
    public Boolean updateOrder(String orderCode,String orderStatus) throws Exception{
        ServiceOrder order = baseMapper.selectOne(Wrappers.<ServiceOrder>lambdaQuery()
                .eq(ServiceOrder::getOrderCode, orderCode));
        if (order.getOrderStatus().equals(ORDER_CANCEL)) {
            throw new Exception("该订单用户已取消订单,您无法继续操作");
        }else if (Integer.parseInt(orderStatus) < Integer.parseInt(order.getOrderStatus())){
            ServiceOrder serviceOrder = new ServiceOrder();
            serviceOrder.setOrderCode(orderCode);
            serviceOrder.setOrderStatus(orderStatus);
            serviceOrder.setOrderTime(new Timestamp(System.currentTimeMillis()));
            if (baseMapper.updateById(serviceOrder)>0) {
                return true;
            }
        }
        throw new Exception("操作失败");
    }

    /**
     * 购买产品
     *
     * @return Boolean
     */
    @Override
    public Boolean shopProduct(ShopDTO shopDTO) throws Exception {
        //todo 订单状态orderStatus： 1.服务完成 2.正在服务 3.审核通过，等待服务 4.待审核 99.用户取消
        if (productMapper.selectOne(Wrappers.<ServiceProduct>lambdaQuery()
        .eq(ServiceProduct::getProductId,shopDTO.getProductId())).getProductStatus() != 0) {
            if (baseMapper.selectCount(Wrappers.<ServiceOrder>lambdaQuery()
                    .eq(ServiceOrder::getOrderEnterprised,shopDTO.getEnterprisedId())
                    .eq(ServiceOrder::getOrderProduct,shopDTO.getProductId())
                    .ne(ServiceOrder::getOrderStatus,99)
                    .ne(ServiceOrder::getOrderStatus,1))>0) {
                throw new Exception("您有一个相同的订单正在进行中,请切勿重复购买");
            }
            ServiceOrder serviceOrder = new ServiceOrder();
            serviceOrder.setOrderCode(OrderUtils.getOrderCode(shopDTO.getEnterprisedId().intValue()));
            serviceOrder.setOrderProduct(shopDTO.getProductId().toString());
            ServiceProduct serviceProduct = productMapper.selectOne(Wrappers.<ServiceProduct>lambdaQuery()
                    .eq(ServiceProduct::getProductId, shopDTO.getProductId()));
            serviceOrder.setOrderMechanism(serviceProduct.getProductMechanism());
            serviceOrder.setOrderEnterprised(shopDTO.getEnterprisedId().toString());
            serviceOrder.setOrderStatus("4");
            serviceOrder.setOrderTime(new Timestamp(System.currentTimeMillis()));
            serviceOrder.setOrderRemarks(shopDTO.getOrderRemarks());
            if (baseMapper.insert(serviceOrder)>0) {
                return true;
            }
        }else {
            throw new Exception("该产品已下架不能购买");
        }

        throw new Exception("购买失败");
    }

    /**
     * 取消购买产品 在订单状态待审核之前可以取消
     *
     * @return Boolean
     */
    @Override
    public Boolean refundProduct(String userId,String orderCode,String orderCause) throws Exception {
        int string = 3;
        //todo 订单状态orderStatus： 1.服务完成 2.正在服务 3.审核通过，等待服务 4.待审核 99.用户取消  审核通过，等待服务前可取消
        ServiceOrder order = baseMapper.selectOne(Wrappers.<ServiceOrder>lambdaQuery()
                .eq(ServiceOrder::getOrderCode, orderCode)
                .eq(ServiceOrder::getOrderEnterprised, userId));
        boolean b = order != null && (order.getOrderStatus().equals(ORDER_ADUIT) || order.getOrderStatus().equals(ORDER_WAIT));
        if (b) {
            ServiceOrder serviceOrder = new ServiceOrder();
            serviceOrder.setOrderCode(orderCode);
            serviceOrder.setOrderStatus("99");
            Timestamp createTime =new Timestamp(System.currentTimeMillis());
            System.out.println(createTime);
            serviceOrder.setOrderTime(createTime);
            serviceOrder.setOrderCause(orderCause);
            if (orderCause.length() <= string) {
                throw new Exception("请填写原因，不得小于3个字");
            }else {
                if (baseMapper.updateById(serviceOrder)>0) {
                    return true;
                }
            }
        }else if (order.getOrderStatus().equals(ORDER_CANCEL) ){
            throw new Exception("订单已取消订单，不可重复操作");
        }else if (order.getOrderStatus().equals(ORDER_FULFILL) || order.getOrderStatus().equals(ORDER_IN) ){
            throw new Exception("订单为服务状态，不可取消");
        }
        return  false;
    }


}
